import React, {
	Component
} from 'react';
import {
	observable,
	action,
	computed,
	toJS,
} from 'mobx';
import {
	Tools,
	Modal,
	Bubble
} from "weaver-mobile";
import * as api from '../../apis/secondaryVerification';
const getLabel = Tools.getLabel;
const prompt = Modal.prompt;

class SecondaryVerificationStore {
	get PLEASEINPUTLOGINPASSWORD (){
		return getLabel(504331, '请先输入登录密码');
	}
	get CANCEL(){
		return getLabel(201, '取消');
	}
	get SURE(){
		return getLabel(826, '确定');
	}
	get LOGINPASSWORD (){
		return getLabel(388431, '登录密码');
	}
	get LOGINPASSWORDERROR(){
		return getLabel('504343', "登录密码错误");
	}
	get PASSWORD (){
		return getLabel(511137, '密码');
	}
	get OLDPASSWORD(){
		return getLabel(32738, '旧密码');
	} 
	get PLEASEINPUTOLDPASS(){
		return getLabel(511058, '请输入旧密码！');
	} 
	get CONFIRMPASSWORD(){
		return getLabel(511112, '确认密码');
	} 
	get VERIFYCODE(){
		return getLabel(511113, '验证码');
	} 
	get INPUTPASSWORDAGAIN(){
		return getLabel(511132, '请再次输入密码');
	} 
	get INPUTVERIFYCODE(){
		return getLabel(511133, '请输入验证码');
	} 
	get NORESTRICTION(){
		return getLabel(511134, '不限制');
	} 
	get UPPERLOWNUMBER(){
		return getLabel(24080, '字母大写、字母小写、数字组合');
	} 

	get LETTERNUMCHAR(){
		return getLabel(24081, '字母、数字、特殊字符组合');
	} 
	get LETTERNUMBER(){
		return getLabel(512563, '字母、数字组合');
	} 
	get PASSWORDCANNOTEMPTY(){
		return getLabel(511135, '密码不能为空');
	} 
	get PLEASECONFIRMPASSWORD(){
		return getLabel(511136, '请确认密码');
	} 
	get NOTEQUAL(){
		return getLabel(504376, '密码确认不正确!');
	} 
	get LESSMINLEN(){
		return getLabel('20172', "密码长度不能小于");
	} 

	get TITLE(){
		return <span className='prompt-title'>{this.PLEASEINPUTLOGINPASSWORD}</span>;
	} 

	@computed get BTN() {
		if (this.hideForm) {
			return {
				type: 'primary',
				size: 'small',
				onClick: () => {
					prompt(this.TITLE, '', [{
						text: this.CANCEL,
						onPress: () => new Promise(resolve => {
							resolve();
						})
					}, {
						text: this.SURE,
						onPress: value => new Promise((resolve, reject) => {
							const callback = (result) => {
								if (result) {
									resolve();
								} else {
									reject();
								}
							}
							this.verifyLoginPassword(value, callback)
						})
					}], 'secure-text', '', [this.LOGINPASSWORD]);
				}
			}
		} else {
			return {
				type: 'primary',
				onClick: () => this.saveForm()
			}
		}

	}

	history = null;

	@observable hideForm = true;

	@observable isSetted = false;

	@action isVerify = () => {
		api.isSettedSecondaryPwd().then(datas => {
			const {
				isSetted
			} = datas;

			this.isSetted = isSetted;

			this.initFormValue(isSetted);
		}, error => {});
	}

	initFormValue = (isSetted) => {
		if (!isSetted) {
			this.values = ['', '', ''];
		} else {
			this.values = ['', '', '', ''];
		}
	}

	@action verifyLoginPassword = (password, callback) => {
		api.checkPassword({
			password
		}).then(datas => {
			const {
				result
			} = datas;

			callback && callback(result);

			if (result) {
				this.showForm();
			} else {
				this.showErrorInfo();
			}
		}, error => {});
	}

	showForm = () => {
		this.callFormApi();
		this.hideForm = false;
	}

	showIntroduction = () => {
		this.hideForm = true;
		this.isSetted = true;
		this.emptyValues();
	}

	emptyValues = () => {
		this.values.forEach((value, index) => {
			this.values[index] = '';
		});
	}

	showErrorInfo = () => {
		Bubble.warning(this.LOGINPASSWORDERROR);
	}

	@computed get whatIsSv() {
		if (!this.isSetted) {
			return `• ${getLabel('504320', "什么是二次验证密码？")}<br />${getLabel('506871', "用于身份确认的二次验证密码")}，${getLabel('504322', "为保安全性，请设置为和登录密码不同的密码。")}`
		} else {
			return `<span>${getLabel('504323',"二次验证密码状态")} :<b>${getLabel('504324',"已设置")}</b> </span>
			<br/> <span>• ${getLabel('504325', "二次验证密码可以自行停用吗？")}</span> 
			<br/> <span>${getLabel('504326', "不可以，只能由管理员操作。")}</span> 
			<br/> <span>• ${getLabel('504327', "二次验证密码忘记了怎么办？")}</span> 
			<br/> <span>${getLabel('504328', "请联系系统管理员解决。")}</span> `
		}
	}

	@computed get btn_name() {
		if (this.hideForm) {
			if (!this.isSetted) {
				return getLabel('504329', "立即设置")
			} else {
				return getLabel('504330', "修改");
			}
		} else {
			return getLabel(86, "保存");
		}
	}

	minpasslen = 1;

	@observable passwordComplexity = '0';

	@computed get labels() {
		const base = [this.PASSWORD, this.CONFIRMPASSWORD, this.VERIFYCODE];
		if (!this.isSetted) {
			return base;
		} else {
			base.unshift(this.OLDPASSWORD);
			return base;
		}
	}

	keys = ['a', 'b', 'c', 'd'];

	isEqualToLastLoginPass = false;

	isEqualToLastSecVerify = false;

	@computed get placeholders() {
		const placeholders = [this.INPUTPASSWORDAGAIN, this.INPUTVERIFYCODE];

		if (this.passwordComplexity === '0') {
			placeholders.unshift(this.NORESTRICTION);
		} else if (this.passwordComplexity === '1') {
			placeholders.unshift(this.UPPERLOWNUMBER);
		} else if (this.passwordComplexity === '2'){
			placeholders.unshift(this.LETTERNUMCHAR);
		} else if (this.passwordComplexity === '3'){
			placeholders.unshift(this.LETTERNUMBER);
		}
		if (this.isSetted) {
			// placeholders.unshift(placeholders[0]);
			placeholders.unshift('');
		}
		return placeholders;
	}

	@observable values = [];

	@observable date = new Date();

	@action handleFormChange = (value, index) => {
		this.values[index] = value;
	}

	@action handleFormBlur = (value, index) => {
		if (!this.isSetted) {
			if (index === 0) {
				this.verifyIsEqualToLoginPass(value);
			}
		} else {
			if (index === 0) {
				this.verifyIsEqualToLastSecVerify(value);
			}
			if (index === 1) {
				this.verifyIsEqualToLoginPass(value);
			}
		}
	}

	@action callFormApi = () => {
		api.getSecondaryPwdForm().then(data => {
			const {
				minpasslen,
				passwordComplexity,
			} = data;

			this.minpasslen = minpasslen;
			this.passwordComplexity = passwordComplexity;
		}, error => {});
	}

	saveForm = () => {
		const verifyResult = this.verifyForm();

		if (verifyResult) {
			const getParams = () => {
				let keys;
				if (!this.isSetted) {
					keys = ['secondaryPwd1', 'secondaryPwd2', 'validatecode'];
				} else {
					keys = ['oldSecondaryPwd', 'newSecondaryPwd1', 'newSecondaryPwd2', 'validatecode'];
				}
				const params = {};
				keys.forEach((key, index) => {
					const value = this.values[index];
					Object.assign(params, {
						[key]: value
					});
				});
				return params;
			}
			const params = getParams();
			api.saveSecondaryPwd(params).then(data => {
				const {
					sign,
				} = data;
				if (sign === '1') {
					Bubble.success(data.message);
					this.showIntroduction();
				} else {
					Bubble.warning(data.message);
					this.refreshVerifyCode();
				}
			}, error => {});
		}
	}

	verifyForm = () => {
		let verifyResult = true;
		const rules = ['verifyIsFill', this.isEqualToLastLoginPass, 'verifyIsEqual', 'verifyMinpasslen', 'verifyPasswordComplexity'];
		if (this.isSetted) {
			rules.splice(2, 0, this.isEqualToLastSecVerify)
		}
		rules.forEach((rule, index) => {
			if (verifyResult) {
				let result;
				if (typeof rule === 'string') {
					result = this[rule]();
				} else {
					result = rule;
					if (!rule) {
						if (index === 1) {
							Bubble.warning(getLabel('504375', "二次验证密码不能和登录密码相同"));
						}
						if (index === 2) {
							Bubble.warning(getLabel('504374', "旧密码校验不通过！"));
						}
					}
				}

				verifyResult = result;
			} else {
				this.refreshVerifyCode()
			}
		})
		return verifyResult;
	}

	verifyIsFill = () => {
		const isFill = this.values.every(value => value !== '');
		if (isFill) {
			return true
		} else {
			const index = this.values.findIndex(value => value === '');
			const warnings = [this.PASSWORDCANNOTEMPTY, this.PLEASECONFIRMPASSWORD, this.INPUTVERIFYCODE];
			if (this.isSetted) {
				warnings.unshift(this.PLEASEINPUTOLDPASS);
			}
			Bubble.warning(warnings[index]);
		}
	}

	verifyMinpasslen = () => {
		const newPassIndex = this.values.length - 3;
		const passLen = this.values[newPassIndex].length;

		if (passLen < this.minpasslen) {
			Bubble.warning(`${this.LESSMINLEN}${this.minpasslen}`);
		} else {
			return true;
		}

	}

	verifyPasswordComplexity = () => {
		const test = (value, regExps) => {
			return regExps.every(regExp => regExp.test(value))
		}
		const newPassIndex = this.values.length - 3;
		const value = this.values[newPassIndex];

		if (this.passwordComplexity == '1') {
			const regExps = [/[a-z]+/, /[A-Z]+/, /\d+/];
			if (!test(value, regExps)) {
				Bubble.warning(getLabel('512768',"新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！"));
				return;
			}
		}
		if (this.passwordComplexity == '2') {
			const regExps = [/[a-zA-Z_]+/, /\W+/, /\d+/];
			if (!test(value, regExps)) {
				Bubble.warning(getLabel('512769',"新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！"));
				return;
			}
		}
		if (this.passwordComplexity == '3') {
			const regExps = [/[a-zA-Z_]+/, /\d+/];
			if (!test(value, regExps)) {
				Bubble.warning(getLabel('512767', "新密码不符合要求，必须包含字母、数字！请重新输入！"));
				return;
			}
		}

		return true;
	}

	verifyIsEqual = () => {
		const newPassIndex = this.values.length - 3;
		const password = this.values[newPassIndex];
		const confirmPassword = this.values[newPassIndex + 1];

		if (password === confirmPassword) {
			return true;
		} else {
			Bubble.warning(this.NOTEQUAL);
		}
	}

	verifyIsEqualToLoginPass = (password) => {
		api.checkNewSecondaryPwd({
			secondaryPwd1: password
		}).then(data => {
			const {
				result
			} = data;

			this.isEqualToLastLoginPass = result;

			if (!result) {
				Bubble.warning(getLabel('504375', "二次验证密码不能和登录密码相同"));
			}
		}, error => {});
	}

	verifyIsEqualToLastSecVerify = (password) => {
		api.checkOldSecondaryPwd({
			oldSecondaryPwd: password
		}).then(data => {
			const {
				result
			} = data;

			this.isEqualToLastSecVerify = result;

			if (!result) {
				Bubble.warning(getLabel('504374', "旧密码校验不通过！"));
			}
		}, error => {});
	}

	refreshVerifyCode = () => {
		this.date = new Date();
	}

}
export const secondaryVerificationStore = new SecondaryVerificationStore();